package com.hskn.hss.module.role.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.constant.CommonConstant;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.core.utils.spring.SpringUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.operatedauthor.entity.SysRoleMenu;
import com.hskn.hss.module.operatedauthor.mapper.SysRoleMenuMapper;
import com.hskn.hss.module.operatedauthor.service.ISysRoleMenuService;
import com.hskn.hss.module.permissionRole.entity.SysPermissionRole;
import com.hskn.hss.module.permissionRole.mapper.SysPermissionRoleMapper;
import com.hskn.hss.module.permissionRole.service.ISysPermissionRoleService;
import com.hskn.hss.module.role.entity.SysRole;
import com.hskn.hss.module.role.mapper.SysRoleMapper;
import com.hskn.hss.module.role.service.SysRoleService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.user.service.impl.UserServiceImpl;
import com.hskn.hss.module.userrole.entity.SysUserRole;
import com.hskn.hss.module.userrole.mapper.SysUserRoleMapper;
import com.hskn.hss.module.userrole.service.impl.SysUserRoleServiceImpl;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2020-11-16
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    SysRoleMapper sysRoleMapper;
    @Autowired
    private ISysPermissionRoleService sysPermissionRoleService;
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;
    @Resource
    private SysPermissionRoleMapper sysPermissionRoleMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private IUserService userService;


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult insertRole(JSONObject params) {

        String username = LoginUtils.getUser().getAccount();
        SysRole sysRole = JSON.parseObject(params.getString("data"), new TypeReference<SysRole>() {
        });
        sysRole.setId(StringUtils.uuid());
        sysRole.setCreateBy(username);
        sysRole.setCreateTime(new Date());
        int i = sysRoleMapper.insert(sysRole);

        // 添加对应的 事务到 角色权限关联表
        SysPermissionRole sysPermissionRole = new SysPermissionRole();
        sysPermissionRole.setRoleid(sysRole.getId());

        String permissionRoleId = sysRole.getPermissionRoleId();
        if (!StringUtils.isEmpty(permissionRoleId)) {
            String[] permissionRoles = permissionRoleId.split(",");
            if (permissionRoles.length == 1) {
                sysPermissionRole.setPermissionid(permissionRoles[0]);
            } else if (permissionRoles.length > 1) {
                sysPermissionRole.setPermissionid("4");
                sysPermissionRole.setDeptvalues(permissionRoleId);
            }
        } else {
            sysPermissionRole.setPermissionid("1");
        }
        JSONObject param = new JSONObject().fluentPut("data", sysPermissionRole);
        try {
            sysPermissionRoleService.insert(param);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
        }

        List<SysRoleMenu> sysRoleMenuList = sysRole.getSysRoleMenu();
        if (!CollectionUtils.isEmpty(sysRoleMenuList)) {
            //添加对应的 操作权限
            for (SysRoleMenu obj : sysRole.getSysRoleMenu()) {
//                if(CollectionUtils.isEmpty(obj)){
//                    continue;
//                }
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setMenuid(obj.getMenuid());
                sysRoleMenu.setButtonid(obj.getButtonid());
                sysRoleMenu.setRoleid(sysRole.getId());

                JSONObject rolemenuParam = new JSONObject().fluentPut("data", sysRoleMenu);
                try {
                    sysRoleMenuService.insert(rolemenuParam);
                } catch (HssException e) {
                    e.printStackTrace();
                    log.error("报错ERROR", e);
                }
            }
        }
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult updateRole(JSONObject params) throws HssException {

        String username = LoginUtils.getUser().getAccount();
        SysRole sysRole = params.getObject("data", SysRole.class);
        sysRole.setUpdatBy(username);
        sysRole.setUpdateTime(new Date());
        int i = sysRoleMapper.updateById(sysRole);
        List<SysUserRole> userRoleList = SpringUtils.getBean(SysUserRoleServiceImpl.class).getSysUserRoleListByRoleId(sysRole.getId());
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(userRoleList)) {
            List<User> userList = SpringUtils.getBean(UserMapper.class).selectList(
                    new QueryWrapper<User>().lambda().in(User::getUid,userRoleList.stream().map(SysUserRole::getUserid).collect(Collectors.toList())));
            if(sysRole.getId().equals("00000000")){
                userList.forEach(user -> user.setIsAdmin(1));
            }else {
                userList.forEach(user -> user.setIsAdmin(2));
            }
            SpringUtils.getBean(UserServiceImpl.class).updateBatchById(userList);
        }
        // 添加对应的 事务到 角色权限关联表
        sysPermissionRoleService.deleteByMap(sysRole.getId());
        SysPermissionRole sysPermissionRole = new SysPermissionRole();
        sysPermissionRole.setRoleid(sysRole.getId());

        String permissionRoleId = sysRole.getPermissionRoleId();
        if (!StringUtils.isEmpty(permissionRoleId)) {
            String[] permissionRoles = permissionRoleId.split(",");
            if (permissionRoles.length == 1) {
                sysPermissionRole.setPermissionid(permissionRoles[0]);
            } else if (permissionRoles.length > 1) {
                sysPermissionRole.setPermissionid("4");
                sysPermissionRole.setDeptvalues(permissionRoleId);
            }
        } else {
            sysPermissionRole.setPermissionid("1");
        }
        JSONObject param = new JSONObject().fluentPut("data", sysPermissionRole);
        try {
            sysPermissionRoleService.insert(param);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
        }

        //添加对应的 操作权限
        sysRoleMenuService.deleteByMap(sysRole.getId());
        for (SysRoleMenu obj : sysRole.getSysRoleMenu()) {
            obj.setRoleid(sysRole.getId());
            JSONObject rolemenuParam = new JSONObject().fluentPut("data", obj);
            try {
                sysRoleMenuService.insert(rolemenuParam);
            } catch (HssException e) {
                e.printStackTrace();
                log.error("报错ERROR", e);
            }
        }

        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult deleteroleByid(JSONObject params) throws HssException {
        String id = params.getString("id");
        int i = sysRoleMapper.deleteById(id);
        sysRoleMenuService.deleteByMap(id);
        sysPermissionRoleService.deleteByMap(id);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }
    @Override
    public AjaxResult deletebatchbyid(SysRole sysRole) throws HssException {
        String ids = sysRole.getIds();
        String[] idArray = ids.split(",");
        sysRoleMapper.deleteBatchIds(Arrays.asList(idArray));
        for (String id:
        idArray) {
            sysRoleMenuService.deleteByMap(id);
            sysPermissionRoleService.deleteByMap(id);

        }

        return AjaxResult.success("操作成功");
    }
    @Override
    public SysRole getRoleById(JSONObject params) throws HssException {
        String roleId = params.getString("id");
        SysRole sysRole = sysRoleMapper.selectById(roleId);
        if (null == sysRole) {
            return null;
        }
        QueryWrapper<SysPermissionRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysPermissionRole::getRoleid, roleId);
        SysPermissionRole sysPermissionRole = sysPermissionRoleMapper.selectOne(queryWrapper);
        if (null != sysPermissionRole) {
            sysRole.setPermissionRoleId(sysPermissionRole.getPermissionid());
            if (CommonConstant.SYS_PERMISSION_CUSTOM.equals(sysPermissionRole.getPermissionid())) {
                sysRole.setDeptvalues(sysPermissionRole.getDeptvalues());
            }
        }
        Map param = new HashMap();
        param.put("roleid", roleId);
        List<SysRoleMenu> rolemenulist = sysRoleMenuMapper.selectByMap(param);
        sysRole.setSysRoleMenu(rolemenulist);
        return sysRole;
    }

    @Override
    public JSONObject getRoleList(JSONObject params) {
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();

        Map<String, Object> map = new HashMap();
        map.put("roleName", params.getString("rolename"));
        map.put("roleCode", params.getString("rolecode"));


        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(map, false);
        queryWrapper.orderByDesc("roleCode");

        Page<SysRole> rolePage = new Page<>(page, size, true);
        IPage<SysRole> iPage = sysRoleMapper.selectPage(rolePage, queryWrapper);
        for (SysRole role : iPage.getRecords()) {
            QueryWrapper<SysPermissionRole> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(SysPermissionRole::getRoleid, role.getId());
            SysPermissionRole sysPermissionRole = sysPermissionRoleMapper.selectOne(queryWrapper1);
            if (sysPermissionRole != null) {
                role.setPermissionRoleId(sysPermissionRole.getPermissionid());
                if (CommonConstant.SYS_PERMISSION_CUSTOM.equals(sysPermissionRole.getPermissionid())) {
                    role.setDeptvalues(sysPermissionRole.getDeptvalues());
                }
            }

            Map param = new HashMap();
            param.put("roleid", role.getId());
            List<SysRoleMenu> rolemenulist = sysRoleMenuMapper.selectByMap(param);
            role.setSysRoleMenu(rolemenulist);

            //角色绑定人数
            QueryWrapper<SysUserRole> querySysUserRole = new QueryWrapper<>();
            querySysUserRole.lambda().eq(SysUserRole::getRoleid, role.getId());
            Integer bindUserCount = sysUserRoleMapper.selectCount(querySysUserRole);
            role.setBindUserCount(bindUserCount);
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("rolelist", iPage.getRecords());
        return json;
    }

    /**
     * 选择权限查询，不是超管不返回超管
     * @return
     */
    @Override
    public List<SysRole> selectRoleList() {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRole::getStatus,"0");
        Integer loginUserIdentity = LoginUtils.getLoginUserIdentity();
        if(loginUserIdentity==2){
            queryWrapper.lambda().ne(SysRole::getId,"00000000");
            queryWrapper.lambda().ne(SysRole::getRoleType,1);
        }
        return list(queryWrapper);
    }

    @Override
    public AjaxResult changeStatus(SysRole sysRole) throws HssException {

        String username = LoginUtils.getUser().getAccount();
        String ids = sysRole.getIds();
        String[] idArray = ids.split(",");
        sysRole.setUpdatBy(username);
        sysRole.setUpdateTime(new Date());

        UpdateWrapper<SysRole> sysRoleUpdateWrapper = new UpdateWrapper<>();
        sysRoleUpdateWrapper.lambda().in(SysRole::getId, idArray);

        int i = sysRoleMapper.update(sysRole,sysRoleUpdateWrapper);
       // int i = sysRoleMapper.updateById(sysRole);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }
}
